use rocket::http::Status;
use rocket::Request;
use rocket::request::{FromRequest, Outcome};
use crate::tools::validation;

pub struct Authorized {}

#[rocket::async_trait]
impl<'r> FromRequest<'r> for Authorized {
    type Error = ();

    async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
        let auth_header = request.headers().get_one("Authorization");
        println!("Auth header: {:?}", auth_header);
        match check_data_from_auth_header(auth_header) {
            Ok(vec_header) => match validation(vec_header[1]) {
                Ok(_) => Outcome::Success(Authorized {}),
                Err(_) => Outcome::Error((Status::Unauthorized,())),
            },
            Err(_) => Outcome::Error((Status::Unauthorized,())),
        }
    }
}

// check data from request auth
fn check_data_from_auth_header(auth_header:Option<&str>) -> Result<Vec<&str>,()>{
    return if let Some(auth_string) = auth_header {
        let vec_header = auth_string.split_whitespace().collect::<Vec<_>>();
        if vec_header.len() != 2 && !vec_header[0].is_empty() && !vec_header[1].is_empty(){
            Err(())
        }else {
            Ok(vec_header)
        }
    }else {
        Err(())
    };
}